<template>
  <el-card class="el-card--has-heading success">
    <div slot="header" class="v-card__headerInner">
      <p>维保商品</p>
      <transition name="el-zoom-in-center">
        <div v-show="showTip">
          <p class="v-card__header-tip">单击【销量、推荐、状态】可进行修改</p>
        </div>
      </transition>
      <el-button
        class="v-card__headerAction"
        type="text"
        @click="onClickCreate"
        v-auth:[$P.business.maintenanceGoods.create]
      >{{showForm ? '返回列表' : '创建商品'}}</el-button>
    </div>
    <MaintenanceGoodsForm
      :record="record"
      :supplySelects="supplySelects"
      :categorySelects="categorySelects"
      @submit="handleSubmit"
      v-loading="formLoading"
      ref="form"
      v-if="showForm"
    />
    <v-table
      :dataSource="dataSource"
      :columns="filterColumn(columns,[$P.business.maintenanceGoods.update,$P.business.maintenanceGoods.delete])"
      :loading="loading"
      :total="total"
      v-else
      v-bind="bindProps"
      v-on="bindListeners"
    >
      <template slot="toolbar">
        <el-form inline size="small" :model="query" ref="query" class="flex flex-wrap">
          <el-form-item prop="goodsName">
            <el-input placeholder="请输入商品名称" v-model.trim="query.goodsName" />
          </el-form-item>
          <el-form-item prop="goodsPick">
            <el-select v-model="query.goodsPick" placeholder="请选择否推荐">
              <el-option
                v-for="(it, i) in commonLogical"
                :key="i"
                :label="it.label"
                :value="it.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="goodsState">
            <el-select v-model="query.goodsState" placeholder="请选择商品状态">
              <el-option
                v-for="(it, i) in onlineStatus"
                :key="i"
                :label="it.label"
                :value="it.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="goodsSupplier">
            <el-select v-model="query.goodsSupplier" placeholder="请选择供应商">
              <el-option
                v-for="(it, i) in supplySelects"
                :key="i"
                :label="it.label"
                :value="it.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="sortType">
            <el-select v-model="query.sortType" placeholder="请选择价格排序">
              <el-option
                v-for="(it, i) in priceSortTypes"
                :key="i"
                :label="it.label"
                :value="it.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="success" @click="handleSearch">查询</el-button>
            <el-button type="warning" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </template>
    </v-table>

    <Modal
      title="修改销量"
      :loading="volumeLoading"
      :visible.sync="volumeVisible"
      :width="$V.size.sm"
      :onOk="handleSubmitVolume"
      :onCancel="handleCloseVolume"
      :okText="$t('updateText')"
    >
      <VolumeForm :record="volumeRecord" ref="volumeForm" />
    </Modal>
  </el-card>
</template>

<script>
import {
  getMaintenanceGoodsList,
  createMaintenanceGoods,
  updateMaintenanceGoods,
  deleteMaintenanceGoods,
  getMaintenanceGoodsById,
  getMaintenanceSupplierSelects,
  getMaintenanceCategorySelects,
  offlineMaintenanceGoods,
  onlineMaintenanceGoods,
  recommendMaintenanceGoods,
  unrecommendedMaintenanceGoods,
  updateMaintenanceVolumn
} from '@/api'

/* components
---------------------------------------------------------------- */
import MaintenanceGoodsForm from './components/MaintenanceGoodsForm'
import VolumeForm from './components/VolumeForm'
import { Query } from '@/mixins'

/* model
---------------------------------------------------------------- */
import { primaryKey } from './model'
import {
  onlineStatusEnum,
  commonLogicalEnum,
  priceSortTypeEnum
} from '@/core/enum'

export default {
  mixins: [Query('query')],

  data () {
    return {
      showTip: false,

      total: 0,
      dataSource: [],
      loading: false,
      columns: [
        { prop: 'goodsName', label: '名称' },
        {
          prop: 'goodsSummary',
          label: '简介',
          minWidth: this.$V.cellSize.desc
        },
        {
          prop: 'goodsPriceOriginal',
          label: '原价',
          width: this.$V.cellSize.price
        },
        {
          prop: 'goodsPriceDiscount',
          label: '折扣价',
          width: this.$V.cellSize.price
        },
        {
          prop: 'goodsSalesVolume',
          label: '销量',
          formatter: (row) => (
            <el-link
              type="success"
              onClick={() => {
                this.volumeRecord = {
                  goodsId: row['goodsId'],
                  goodsSalesVolume: row['goodsSalesVolume']
                }
                this.volumeVisible = true
              }}
            >
              {row['goodsSalesVolume']}
            </el-link>
          )
        },
        {
          prop: 'goodsPick',
          label: '推荐',
          width: this.$V.cellSize.logic,
          formatter: (row) => (
            <el-link
              type={!row['goodsPick'] ? 'danger' : 'success'}
              onClick={() => this.onToggleRecommend(!row['goodsPick'], row)}
            >
              {row['goodsPick'] ? '是' : '否'}
            </el-link>
          )
        },
        {
          prop: 'goodsStateValue',
          label: '状态',
          width: this.$V.cellSize.status,
          formatter: (row) => (
            <el-link
              type={
                row['goodsState'] !== onlineStatusEnum.online
                  ? 'danger'
                  : 'success'
              }
              onClick={() =>
                this.onToggleOnline(
                  row['goodsState'] !== onlineStatusEnum.online,
                  row
                )
              }
            >
              {row['goodsStateValue'] ||
                onlineStatusEnum[onlineStatusEnum.online]}
            </el-link>
          )
        },
        { prop: 'goodsSupplierName', label: '所属供应商' },

        {
          prop: 'goodsCreateTime',
          label: '创建时间',
          width: this.$V.cellSize.date,
          formatter: (row) => this.$formatTime(row['goodsCreateTime'])
        },
        { prop: 'goodsCreateUserName', label: '创建人' },
        {
          prop: 'goodsUpdateTime',
          label: '修改时间',
          width: this.$V.cellSize.date,
          formatter: (row) => this.$formatTime(row['goodsUpdateTime'])
        },
        { prop: 'goodsUpdateUserName', label: '修改人' },
        {
          label: '操作',

          minWidth: this.$V.cellSize.action,
          formatter: this.getActionDecorator([
            {
              icon: 'el-icon-edit',
              action: this.onClickUpdate,
              type: 'primary',
              auth: this.$P.business.maintenanceGoods.update
            },
            {
              icon: 'el-icon-delete',
              action: this.onClickDelete,
              type: 'danger',
              auth: this.$P.business.maintenanceGoods.delete
            }
          ])
        }
      ],
      record: {},
      query: {
        goodsName: '',
        goodsState: '',
        goodsPick: '',
        goodsSupplier: '',
        sortType: ''
      },
      volumeRecord: {
        goodsId: '',
        goodsSalesVolume: ''
      },

      // -------- Form ----------
      showForm: false,
      // 供应商列表
      supplySelects: [],
      // 分类列表
      categorySelects: [],

      formLoading: false,
      actionType: '',
      // -------- !Form ----------

      // -------- Modal ----------
      volumeVisible: false,
      volumeLoading: false
      // -------- !Modal ----------
    }
  },
  methods: {
    // Requests
    // ------------------------------------------
    getMaintenanceGoodsList (fn) {
      return this.Catch(getMaintenanceGoodsList, {
        onOk (res) {
          this.dataSource = res.data.data
          this.total = res.data.total
        }
      })('loading', (fn || this.$noop)(this.query))
    },

    getMaintenanceGoodsById (id, { onOk, onError }) {
      return this.Catch(getMaintenanceGoodsById, {
        onOk,
        onError
      })('loading', id)
    },

    /**
     * 供应商下拉列表
     */
    getMaintenanceSupplierSelects (loading) {
      if (this.supplySelects.length) {
        return Promise.resolve()
      }
      return this.Catch(getMaintenanceSupplierSelects, {
        onOk ({ data }) {
          this.supplySelects = data.map((it) => ({
            label: it.supplierName,
            value: it.supplierId
          }))
        }
      })(loading)
    },

    /**
     * 维保分类下拉列表
     */
    getMaintenanceCategorySelects (loading) {
      if (this.categorySelects.length) {
        return Promise.resolve()
      }
      return this.Catch(getMaintenanceCategorySelects, {
        onOk ({ data }) {
          this.categorySelects = data.map((it) => ({
            label: it.classifyName,
            value: it.classifyId
          }))
        }
      })(loading)
    },

    deleteMaintenanceGoods (id, { onOk }) {
      return this.Catch(deleteMaintenanceGoods, {
        onOk
      })(null, id)
    },

    recommendMaintenanceGoods (id, { onOk }) {
      return this.Catch(recommendMaintenanceGoods, {
        onOk
      })(null, id)
    },
    unrecommendedMaintenanceGoods (id, { onOk }) {
      return this.Catch(unrecommendedMaintenanceGoods, {
        onOk
      })(null, id)
    },
    onlineMaintenanceGoods (id) {
      return this.Catch(onlineMaintenanceGoods, {
        onOk () {
          this.$message.success('上线成功')
          this.getMaintenanceGoodsList()
        }
      })(null, id)
    },
    offlineMaintenanceGoods (id) {
      return this.Catch(offlineMaintenanceGoods, {
        onOk () {
          this.$message.success('下线成功')
          this.getMaintenanceGoodsList()
        }
      })(null, id)
    },

    createMaintenanceGoods (data) {
      return this.Catch(createMaintenanceGoods, {
        onOk () {
          this.$message.success(this.$t('createOk'))
          this.showForm = false
          this.getMaintenanceGoodsList()
        }
      })('formLoading', data)
    },

    updateMaintenanceGoods (id, data) {
      return this.Catch(updateMaintenanceGoods, {
        onOk () {
          this.$message.success(this.$t('updateOk'))
          this.showForm = false
          this.getMaintenanceGoodsList()
        }
      })('formLoading', id, data)
    },

    updateMaintenanceVolumn (id, data) {
      return this.Catch(updateMaintenanceVolumn, {
        onOk () {
          this.$message.success(this.$t('updateOk'))
          this.volumeVisible = false
          this.getMaintenanceGoodsList()
        }
      })('volumeLoading', id, data)
    },

    // Table
    // ------------------------------------------

    onClickDelete (row) {
      this.ConfirmDelete({
        onOk: () =>
          this.deleteMaintenanceGoods(row[primaryKey], {
            onOk () {
              this.$message.success(this.$t('deleteOk'))
              this.getMaintenanceGoodsList()
            }
          })
      })
    },

    /**
     * 切换推荐
     */
    onToggleRecommend (recommended, row) {
      const message = recommended
        ? '确认要推荐所选商品吗？'
        : '确认要取消推荐所选商品吗？'
      const request = recommended
        ? this.recommendMaintenanceGoods
        : this.unrecommendedMaintenanceGoods
      const tip = recommended ? '推荐成功' : '取消推荐成功'
      this.MessageBox({
        message,
        type: 'warning',
        onOk: () =>
          request(row[primaryKey], {
            onOk () {
              this.$message.success(tip)
              this.getMaintenanceGoodsList()
            }
          })
      })
    },
    /**
     * 切换上下线
     */
    onToggleOnline (willOnline, row) {
      this.ConfirmToggleOnline({
        online: willOnline,
        onOk: () =>
          willOnline
            ? this.onlineMaintenanceGoods(row[primaryKey])
            : this.offlineMaintenanceGoods(row[primaryKey])
      })
    },

    async onClickUpdate (row) {
      try {
        this.assertCanUpdate(row)
        await this.ensureAllFormPrepareData()

        this.actionType = 'update'
        this.getMaintenanceGoodsById(row[primaryKey], {
          onOk ({ data }) {
            this.record = data
            this.showForm = true
          }
        })
      } catch (err) {
        this.$message.warning(err.message)
      }
    },

    async onClickCreate () {
      await this.ensureAllFormPrepareData()
      this.actionType = 'create'
      this.record = {}

      this.showForm = !this.showForm
    },

    // ------------------------------------------ Form 开始------------------------------------------
    ensureAllFormPrepareData () {
      const tasks = [
        this.getMaintenanceSupplierSelects(),
        this.getMaintenanceCategorySelects()
      ]

      return this.Catch(() => Promise.all(tasks), {
        onOk () {},
        onError () {}
      })('loading')
    },

    assertCanUpdate (row) {
      if (row['goodsState'] === onlineStatusEnum.online) {
        throw new Error('上线状态不可编辑')
      }
    },

    handleSubmit (formData) {
      this.actionType === 'create'
        ? this.createMaintenanceGoods(formData)
        : this.updateMaintenanceGoods(formData[primaryKey], formData)
    },

    // ------------------------------------------ Form 结束------------------------------------------

    // ------------------------------------------ Modal 开始------------------------------------------
    handleSubmitVolume () {
      this.$refs.volumeForm.submit((valid, values) => {
        if (valid) {
          this.updateMaintenanceVolumn(
            values['goodsId'],
            values['goodsSalesVolume']
          )
        }
      })
    },
    handleCloseVolume () {
      this.volumeVisible = false
    }
    // ------------------------------------------ Modal 结束------------------------------------------
  },
  computed: {
    onlineStatus () {
      return this.$mapEnumToSelect(onlineStatusEnum)
    },
    commonLogical () {
      return this.$mapEnumToSelect(commonLogicalEnum, {
        valueTransfer: null,
        keyFilter: null
      })
    },
    priceSortTypes () {
      return this.$mapEnumToSelect(priceSortTypeEnum)
    }
  },
  components: { MaintenanceGoodsForm, VolumeForm },

  created () {
    this.getMaintenanceGoodsList()
    this.inject(this.getMaintenanceGoodsList)

    this.getMaintenanceSupplierSelects()

    this.$nextTick(() => (this.showTip = true))
  }
}
</script>
